'use strict';
const mongoose = require('mongoose');
const md5 = require('md5');

let schema = new mongoose.Schema({
    loginId: {
        type: String,
        required: true,
        index: {
            unique: true
        }
    },
    password: String,
    token: String,   //用于非登陆验证
    loginTimes: {
        type: Number,
        "default": 0
    },
    lastLoginIp: String,
    status: {
        type: Number,
        "default": 0   //0代表普通管理员  10代表超级管理员  -1代表该管理员被禁止登陆
    }
});
schema.index({loginId: 1}, {unique: true});
schema.index({loginId: 1, token: 1}, {unique: false});

schema.statics = {
    //验证登陆，如果成功登陆，则返回token
    checkLogin: async function (loginId, password) {
        let admin = await this.findOne({loginId: loginId});
        if (!!admin && admin.password === md5(password)) {
            let token = md5(new Date().getTime().toString());
            await this.update({loginId: loginId}, {$set: {token: token}}).exec();
            return {loginId: loginId, token: token};
        } else {
            return false;
        }
    },
    //验证修改密码，如果成功修改，则返回token
    changePwd: async function (loginId, oldPwd, newPwd) {
        let admin = await this.findOne({loginId: loginId});
        if (!!admin && admin.password === md5(oldPwd)) {
            let token = md5(new Date().getTime().toString());
            let password = md5(newPwd);
            await this.update({loginId: loginId}, {$set: {token: token, password: password}}).exec();
            return {loginId: loginId, token: token};
        } else {
            return false;
        }
    },

    //验证用户token是否合法
    checkToken: async function (loginId, token) {
        let admin = await this.findOne({loginId: loginId, token: token});
        return admin;
    }
};


module.exports = schema;